/*
 * SvrTask.h
 *
 *  Created on: 2012-7-11
 *      Author: ThinkPad
 */

#ifndef SVRTASK_H_
#define SVRTASK_H_

#include "SvrConfig.h"
#include "smart_lock.h"
#include "link_list.h"
#include "http.h"
#include "io_buf.h"
#include "DataClip.h"

#define IP_LEN 32
/*
*svr run live status
*/
enum Svr_Run_Status
{
    SV_NONE = 0,
    SV_INIT = 1,
    SV_HEARTBEAT = 2,
    SV_CLOSE = 3
};
/*
*task status
*/
enum TASK_STATUS
{
    TASK_CLOSE,
    TASK_RUN
};
/*
*task flag
*/
enum TASK_FLAG
{
    TASK_NONE,
    TASK_MARKER,
    TASK_ADD,
    TASK_DEL
};

/*
*live stream task
*/
struct live_stream_task
{
	uint16_t	id; /*stream id ,config id*/
	char		stream_name[FILE_MAX_PATH];	/*stream name ,url path*/
	char		remote_ip[IP_LEN];	/*source ip,addr*/
	uint16_t	addr_port;	/*source port*/
	HTTP_MIME   stream_fmt;	/*stream fmt*/
	time_t      begin_time;				/*task begin time*/
	time_t      end_time;				/*task end time*/
	TASK_FLAG   flag;					/*task flag*/
	TASK_STATUS status;					/*task status*/
	bool		stream_enable;			/*stream is enable*/
	int			ntry_times;
	int			ndelay_times;
	live_stream_task * next;
	live_stream_task * prev;

	live_stream_task()
	{
		id = 0;
		memset(stream_name,'\0',FILE_MAX_PATH);
		memset(remote_ip,'\0',IP_LEN);
		addr_port = 0;
		flag = TASK_NONE;
		status = TASK_CLOSE;
		stream_enable = false;
		ntry_times = 0;
		ndelay_times = 0;
		next = NULL;
		prev = NULL;
	}
};

/*
 * server task class
 */
class SvrTask
{
public:
    SvrTask();
    ~SvrTask();

    Svr_Run_Status  Status;
    TASK_STATUS     svr_heartbeat_task;

public:
    /**
     * init class
     */
    int init(SvrConfig * pconfig);

    /*
    *handle heartbeat data
    */
    int handle_heartbeat_data(char * buf,size_t buf_len);

    /*
	*read  stream config
	*/
	void init_config_stream(void);
	/*
	*live stream task ,function
	*/
	int close_stream_task(uint16_t id);
	void enable_stream_task(uint16_t id);
	uint16_t find_stream_id(char * sname);

	/*
	*if task not find ,is return true
	*/
	bool check_stream_task_is_exit(uint16_t id);

	 /*
	*use it must be carefull
	*task_list_lock, lock do enter call,
	*when you usr completed,then call end_enter
	*/
	live_stream_task * begin_enter(void);
	void end_enter(void);

protected:
	/*
	*live stream task ,manage
	*/
	void alloc_stream_task(live_stream_task ** task);
	void free_stream_task(live_stream_task * task);
	void reset_stream_task(live_stream_task * task);
	void add_stream_task(live_stream_task * task);
	void clear_stream_task(void);

private:
    SvrConfig  * pSvrconfig;

    link_list<live_stream_task> live_stream_task_list;
	link_list<live_stream_task> free_live_stream_task_list;
	smart_lock taskLock;
	bool       lock_flag;
};

#endif /* SVRTASK_H_ */
